import sys
import subprocess

loginPath = "./build/include/login/login"
registerPath = "./build/include/register/register"
uploadPaht = "./build/include/upload/upload"
ip = '127.0.0.1'
LOGIN_PORT = '10000'
REGISTER_PORT = '10001'
UPLOAD_PORT = '10002'

def KillProcessByName(processName):
    try:
        result = subprocess.run(['pgrep', '-f', processName], stdout=subprocess.PIPE, text=True, check=True)
        pids = result.stdout.strip().split('\n')
        for pid in pids:
            subprocess.run(['kill' , pid], check=True)
            print(f'Process {processName} with pid {pid} is killed.')
    except subprocess.CalledProcessError:
        print(f'No process named {processName}.')

def StartCgiProcess(ip, prot, path):
    try:
        result = subprocess.run(['spawn-fcgi', '-a', ip, '-p', prot, '-f', path])
        if result.returncode != 0:
            print(f'Start {path} failed.')
        else:
            print(f'Start {path} success.')
    except subprocess.CalledProcessError:
        print(f'Start {path} failed.')

def Start():
    print('Start the service.')
    StartCgiProcess(ip, LOGIN_PORT, loginPath)
    StartCgiProcess(ip, REGISTER_PORT, registerPath)
    StartCgiProcess(ip, UPLOAD_PORT, uploadPaht)

def Stop():
    print('Stop the service.')
    KillProcessByName(loginPath)
    KillProcessByName(registerPath)
    KillProcessByName(uploadPaht)

def main():
    if len(sys.argv) < 2:
        print('Please input the operation.')
        sys.exit(0)

    operation = sys.argv[1]
    if operation == 'start':
        Start()
    elif operation == 'stop':
        Stop()
    else:
        print('Operation is failed, please input the correct operation.')


if __name__ == '__main__':
    main()